package com.example.lostandfoundsystem.config;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author lucifer
 * @since 2024-07-12-15:31
 */
@Configuration
public class HttpConfig {
    public Connector initConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");    // 如果用户使用http方式进行访问
        connector.setPort(8080);        // 如果用户访问的是80端口
        connector.setSecure(false);     // 如果该连接为跳转，则表示不是一个新的连接对象
        connector.setRedirectPort(443); // 设置转发操作端口
        return connector;
    }

    @Bean
    public TomcatServletWebServerFactory tomcatServletWebServerFactory() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) { // 进行请求处理的上下文配置
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL"); // 设置约束
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*"); // 所有的路径全部进行重定向处理
                securityConstraint.addCollection(collection); // 追加路径映射访问配置
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(initConnector()); // 添加连接器
        return tomcat;
    }
}
